<template>
  <div>
    <el-dialog
      v-toggle-full
      v-loading.lock="loading"
      class="base-dialog storage-order-in-edit"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="title"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <p slot="title">{{ editId ? '编辑入库单信息' : '新增入库单信息' }}</p>
      <el-form
        ref="formData"
        :model="formData"
        :rules="formDataRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="业务类型"
              :label-width="formLabelWidth"
              prop="orderTypeCode"
              :error="errorMsg.orderTypeCode"
            >
              <el-select
                v-model="formData.orderTypeCode"
                placeholder="请选择业务类型"
                filterable
                clearable
                @change="(val) => selectOrderType(val)"
              >
                <el-option
                  v-for="item in orderTypeOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="入库仓库"
              :label-width="formLabelWidth"
              prop="storageId"
              :error="errorMsg.storageId"
            >
              <el-select
                v-model="formData.storageId"
                placeholder="请选择入库仓库"
                filterable
                clearable
                @change="(val) => selectStorage(val)"
              >
                <el-option
                  v-for="item in storageIdData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="入库物料"
              :label-width="formLabelWidth"
              prop="productId"
              :error="errorMsg.productId"
            >
              <el-input
                ref="txtSerialNum"
                v-model="serialNum"
                placeholder="请输入序列号回车/扫描条形码"
                autocomplete="off"
                style="float: left"
                @keyup.enter.native="addProduct"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: left; padding-left: 15px">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="addProductByScanner()"
              >扫码添加</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="selectProductList()"
              >选择物料</el-button
            >
          </el-col>
        </el-row>

        <el-table
          v-if="formData.products.length > 0"
          :data="formData.products"
          :header-cell-style="{ height: '50px' }"
          :cell-style="{ height: '70px', overflow: 'auto' }"
          style="width: 100%; height: auto; overflow: auto"
        >
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="编号">
            <template slot-scope="scope">
              {{ scope.row.number }}
            </template>
          </el-table-column>
          <el-table-column label="名称">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="别名">
            <template slot-scope="scope">
              {{ scope.row.aliasName }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template slot-scope="scope">
              {{ scope.row.size }}
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template slot-scope="scope">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
          <el-table-column label="存储条件">
            <template slot-scope="scope">
              {{ scope.row.storeCondition }}
            </template>
          </el-table-column>
          <el-table-column label="包装单位">
            <template slot-scope="scope">
              {{ scope.row.packingUnit }}
            </template>
          </el-table-column>
          <el-table-column label="实际库存">
            <template slot-scope="scope">
              {{ scope.row.inventory }}
            </template>
          </el-table-column>
          <el-table-column label="入库数量">
            <template slot-scope="scope">
              <el-form-item
                :key="scope.$index"
                :prop="'products.' + scope.$index + '.productCount'"
                label-width="0px"
                :rules="[
                  { required: true, message: '必填项', trigger: 'change' },
                  {
                    validator: validateInputCount(scope.row.productCount),
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.productCount"
                  autocomplete="off"
                  min="0"
                  maxlength="5"
                  placeholder="请输入"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link
                  size="mini"
                  type="primary"
                  @click="deleteProduct(scope.$index)"
                  >删除</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 20px">
          <el-col :span="12">
            <el-form-item
              label="申请人"
              :label-width="formLabelWidth"
              prop="applicantId"
              :error="errorMsg.applicantId"
            >
              <el-select
                ref="selectUser"
                v-model="formData.applicantId"
                :multiple="false"
                filterable
                placeholder="请选择申请人"
                value-key="id"
              >
                <el-option
                  v-for="item in sysUserOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="申请原因"
              :label-width="formLabelWidth"
              prop="remark"
              :error="errorMsg.remark"
            >
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                maxlength="1000"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 选择物料 -->
      <SelectMaterialDialog
        v-if="dialogProductVisible"
        ref="SelectMaterialDialog"
        :dialog-product-visible.sync="dialogProductVisible"
        @confirmSelected="confirmSelected"
      >
      </SelectMaterialDialog>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit('formData', false)"
          >保 存</el-button
        >
        <el-button
          type="primary"
          style="width: 100px"
          @click="onSubmit('formData', true)"
          >保存并提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetConfigByKey } from "../../../../api/System/SystemDict.js";
import { getStorageList, getUserListNoPage, getCurrentUserInfo } from "../../../../api/Material/Common.js";
import { getByNumber } from "../../../../api/Material/Material.js";
import { create, update, getInfo } from "../../../../api/Material/MaterialOrderIn.js";
import SelectMaterialDialog from "../../../../components/SelectMaterialDialog.vue"
export default {
  name: "RKOrderEdit",
  components: { SelectMaterialDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      title: "新增入库单",
      loading: false,
      innerDialogFormVisible: false,
      dialogProductVisible: false,
      formLabelWidth: "100px",
      orderTypeOptions: [],
      storageIdData: [],
      sysUserOptions: [],
      serialNum: '',
      initData: {
        id: 0,
        orderNum: "",
        orderTypeCode: null,
        orderTypeName: "",
        storageId: null,
        storageName: "",
        productCount: 0,
        remark: "",
        applicantId: null,
        applicantName: "",
        products: [],
      },
      formData: {
        id: 0,
        orderNum: "",
        orderTypeCode: null,
        orderTypeName: "",
        storageId: null,
        storageName: "",
        productCount: 0,
        remark: "",
        applicantId: null,
        applicantName: "",
        products: [],
      },
      formDataRules: {
        orderNum: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        orderTypeCode: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        orderTypeName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        storageId: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        storageName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        productCount: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        applicantId: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        remark: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        orderNum: "",
        orderTypeCode: "",
        storageId: "",
        productCount: "",
        remark: "",
        applicantId: "",
      },
      errorMsg: {
        orderNum: "",
        orderTypeCode: "",
        storageId: "",
        productCount: "",
        remark: "",
        applicantId: "",
      },
    };
  },
  watch: {
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    async init() {
      // 查询字典表=>入库单类型
      GetConfigByKey({ configKey: "MaterialOrderIn_OrderTypeCode" }).then((res) => {
        if (res.data != null && res.data.length > 0 && res.data[0].value != null) {
          this.orderTypeOptions = JSON.parse(res.data[0].value);
        }
      });
      await this.getStorageOptions();
      await this.getUserOptions();
      if (this.editId) {
        await this.getDetail();
      } else {
        this.setDefaultUser();
      }
    },
    getUserOptions() {
      this.sysUserOptions = [];
      getUserListNoPage({ userStatus: 1 }).then((res) => {
        this.sysUserOptions = res.data;
      });
    },
    // 设置申请人为默认当前用户
    setDefaultUser() {
      getCurrentUserInfo().then((res) => {
        if (res.code === 200 && res.data != null) {
          this.formData.applicantId = res.data.currentUserId;
          this.formData.applicantName = res.data.name;
        }
      });
    },
    getDetail() {
      getInfo({ id: this.editId }).then((res) => {
        this.formData = res.data
        this.formData.products = res.data.products ? res.data.products : []
      });
    },
    getStorageOptions() {
      return new Promise((resolve) => {
        getStorageList().then((res) => {
          if (res.data.dataList?.length > 0) {
            this.storageIdData = res.data.dataList.map(item => {
              return {
                ...item,
                value: item.id
              }
            });
          }
          resolve();
        });
      })
    },
    selectOrderType(val) {
      var obj = {};
      obj = this.orderTypeOptions.find(function(i) {
        return i.key === val
      });
      this.formData.orderTypeCode = obj.key;
      this.formData.orderTypeName = obj.value;
    },
    selectStorage(val) {
      var obj = {};
      obj = this.storageIdData.find(function(i) {
        return i.id === val
      });
      this.formData.storageId = obj.id;
      this.formData.storageName = obj.name;
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$refs["formData"].resetFields();
      this.$emit("update:editId", "");
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    // 选择物料
    selectProductList() {
      this.dialogProductVisible = true;
    },
    confirmSelected(data) {
      if (data && data.length > 0) {
        const mergeData = this.formData.products.concat(data);
        this.formData.products = this.unique(mergeData, 'productId');
      }
    },
    addProduct() {
      getByNumber({ number: this.serialNum }).then((res) => {
        if (res.data != null) {
          const tempArr = [];
          res.data["value"] = res.data.id;
          res.data["productId"] = res.data.id;
          tempArr.push(res.data);
          const mergeData = this.formData.products.concat(tempArr);
          this.formData.products = this.unique(mergeData, 'productId');
        }
        this.serialNum = "";
        this.$refs["txtSerialNum"].focus();
      });
    },
    addProductByScanner() {
      this.serialNum = "";
      this.$refs["txtSerialNum"].focus();
    },
    deleteProduct(index) {
      this.Helper.deleteConfirm(() => {
        this.formData.products.splice(index, 1)
      });
    },
    unique(arr, u_key) {
      const map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    },
    // 保存&提交
    onSubmit(formId, isSubmit) {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          var productList = [];
          if (this.formData.products?.length > 0) {
            productList = this.formData.products.map(item => {
              return {
                productId: item.productId,
                productNum: item.number,
                productCount: item.productCount
              }
            });
          } else {
            this.$message.error("请添加入库物料清单!");
            return false
          }
          // 获取选中人员
          const val = this.formData.applicantId;
          var userItem = this.sysUserOptions.find(function(i) { return i.id === val });
          this.formData.applicantName = userItem.name;

          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          const { ...formData } = this.formData;
          if (this.formData.id <= 0) {
            create({
              ...formData,
              products: productList,
              isSubmit: isSubmit
            })
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update({
              ...formData,
              products: productList,
              isSubmit: isSubmit
            })
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("orderNum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("orderTypeCode", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("storageId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("productCount", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("applicantId", this.errorMsg, res.msg);
      }
    },
    validateInputCount(val) {
      return function(rule, value, callback) {
        var pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
        const count = Number(value);
        if (isNaN(count)) {
          callback(new Error("格式错误"));
        } else if (!pattern.test(value)) {
          callback(new Error("必须为正整数"));
        } else {
          callback();
        }
      };
    },
  },
};
</script>
<style lang="scss">
.storage-order-in-edit {
  .el-table .cell {
    overflow: visible;
  }
}
</style>
